<?php
namespace App\DesignPattern\Adapter;

use App\DesignPattern\Adapter\DbAdapter;
use App\DesignPattern\Adapter\DriverMysql;

class DbMysql implements DbAdapter
{

    private $mysql;

    public function __construct($host, $user, $pwd, $dbname, $port = null, $charset = "utf8", array $opts = null)
    {
        if(!empty($port)){
            $server = "{$host}:{$port}";
        }else{
            $server = $host;
        }
        $pconnect = isset($opts['pconnect']) ? $opts['pconnect'] : false;
        $newlink = isset($opts['newlink'])  ? $opts['newlink'] : false;
        $clientflag = isset($opts['clientflag'])  ? $opts['clientflag'] : 0;
        $this->mysql = new DriverMysql($server, $user, $pwd, $dbname, $charset, $pconnect, $newlink, $clientflag);
    }

    public function __destruct()
    {
        $this->mysql->close();
    }

    public function prototype()
    {
        return $this->mysql;
    }

    /**
     * mysql函数实现的安全化值
     * @param string $value
     * @return string
     */
    private function parseValue($value){
        return $this->mysql->parseValue($value);
    }

    public function query($sql, array $params = [], callable $callback = null)
    {
        if(!empty($params)){
            $temp = explode('?', $sql);
            $last_sql = "";
            for($i = 0; $i < count($temp) - 1; $i++){
                $last_sql .= $temp[$i] . $this->parseValue($params[$i]);
            }
            $last_sql .= $temp[count($temp) - 1];
            $sql = $last_sql;
        }
        if(stripos($sql, "INSERT") === 0 || stripos($sql, "REPLACE") === 0){
            $this->mysql->execute($sql);
            $id = $this->mysql->getLastInsID();
            return $id; //返回自增ID
        }elseif(stripos($sql, "SELECT") === 0){
            $this->mysql->query($sql, 0);
            if($callback !== null){
                $this->mysql->fetch($callback);
            }else{
                $arr = $this->mysql->getAll();
                return $arr; //返回数组
            }
        }else{
            $rows = $this->mysql->execute($sql);
            return $rows; //返回受影响条数
        }
    }
}